package com.dc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.ResponseResultVO;
import com.dc.entity.InspectionPosition;
import com.dc.entity.InspectionRelation;
import com.dc.entity.InspectionRoute;
import com.dc.entity.QrCodeManagement;
import com.dc.entity.ro.InspectionRouteRO;
import com.dc.exceptions.BizException;
import com.dc.mapper.InspectionPositionMapper;
import com.dc.mapper.InspectionRelationMapper;
import com.dc.mapper.InspectionRouteMapper;
import com.dc.mapper.QrCodeManagementMapper;
import com.dc.service.InspectionRouteService;
import com.dc.util.SnowflakeIdWorker;
import com.dc.util.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.dc.common.ResponseResultVO.*;

@Service
public class InspectionRouteServiceImpl extends ServiceImpl<InspectionRouteMapper, InspectionRoute> implements InspectionRouteService {

    @Resource
    private InspectionRouteMapper inspectionRouteMapper;
    @Resource
    private InspectionPositionMapper positionMapper;
    @Resource
    private InspectionRelationMapper relationMapper;
    @Resource
    private QrCodeManagementMapper qrCodeManagementMapper;


    @Override
    @Transactional
    public ResponseResultVO insertInspectionRoute(InspectionRouteRO ro) {
        if (null != inspectionRouteMapper.selectOne(new QueryWrapper<InspectionRoute>().lambda().eq(InspectionRoute::getName, ro.getName()))) {
            return ResponseResultVO.failResult("路线名称重复");
        }
        InspectionRoute inspectionRoute = new InspectionRoute();
        BeanUtils.copyProperties(ro, inspectionRoute);
        inspectionRoute.setId(SnowflakeIdWorker.generateId());

        if (CollectionUtils.isNotEmpty(ro.getPositionIds())) {
            for (String id : ro.getPositionIds()) {
                InspectionRelation inspectionRelation = new InspectionRelation();
                inspectionRelation.setId(SnowflakeIdWorker.generateId());
                inspectionRelation.setPositionId(Long.valueOf(id));
                inspectionRelation.setRouteId(inspectionRoute.getId());
                relationMapper.insert(inspectionRelation);
            }
        }

        return ResponseResultVO.insertResult(inspectionRouteMapper.insert(inspectionRoute));
    }

    @Override
    public ResponseResultVO insertHaveInspectionRoute(InspectionRouteRO ro) {
        // TODO 校验一个路线下不能重复绑定一个点
        checkParameterIsNotNull(String.valueOf(ro.getPositionId()), "点位id不能为空");
        checkParameterIsNotNull(String.valueOf(ro.getId()), "路线id不能为空");
        InspectionRelation relation = relationMapper.selectOne(new QueryWrapper<InspectionRelation>().lambda()
                .eq(InspectionRelation::getPositionId, ro.getPositionId()).eq(InspectionRelation::getRouteId, ro.getId()));
        if (null != relation) {
            return failResult("当前点位已绑定该路线，请勿重复绑定");
        }
        InspectionRelation inspectionRelation = new InspectionRelation();
        inspectionRelation.setId(SnowflakeIdWorker.generateId());
        inspectionRelation.setPositionId(ro.getPositionId());
        inspectionRelation.setRouteId(ro.getId());

        return ResponseResultVO.insertResult(relationMapper.insert(inspectionRelation));
    }

    @Override
    public ResponseResultVO insertNewInspectionRoute(InspectionRouteRO ro) {
        checkParameterIsNotNull(String.valueOf(ro.getPositionId()), "点位id不能为空");
        checkParameterIsNotNull(String.valueOf(ro.getName()), "路线名称不能为空");
        if (null != inspectionRouteMapper.selectOne(new QueryWrapper<InspectionRoute>().lambda().eq(InspectionRoute::getName, ro.getName()))) {
            return ResponseResultVO.failResult("路线名称重复");
        }
        InspectionRoute inspectionRoute = new InspectionRoute();
        BeanUtils.copyProperties(ro, inspectionRoute);
        inspectionRoute.setId(SnowflakeIdWorker.generateId());
        if (null != ro.getPositionId()) {
            InspectionRelation inspectionRelation = new InspectionRelation();
            inspectionRelation.setId(SnowflakeIdWorker.generateId());
            inspectionRelation.setPositionId(ro.getPositionId());
            inspectionRelation.setRouteId(inspectionRoute.getId());
            relationMapper.insert(inspectionRelation);
        }

        return ResponseResultVO.insertResult(inspectionRouteMapper.insert(inspectionRoute));
    }

    @Override
    @Transactional
    public ResponseResultVO newInspectionRoute(InspectionRouteRO ro) {
        InspectionPosition result = positionMapper.selectById(ro.getPositionId()); //巡检点位表
        if (null != result.getQrId()) {
            return failResult("当前点位已绑定二维码");
        }
        QrCodeManagement qrCodeManagement = qrCodeManagementMapper.selectById(ro.getQrId());
        if (null == qrCodeManagement) {
            return failResult("当前二维码已作废");
        }
        InspectionPosition inspectionPosition = new InspectionPosition();
        inspectionPosition.setId(ro.getPositionId());
        inspectionPosition.setQrId(qrCodeManagement.getId());
        inspectionPosition.setPath(qrCodeManagement.getPath());
        QrCodeManagement qrCodeVO = new QrCodeManagement();
        qrCodeVO.setId(ro.getQrId());
        qrCodeVO.setStatus(1);
        qrCodeManagementMapper.updateById(qrCodeVO);
        int i = positionMapper.updateById(inspectionPosition);
        if (i == 0) {
            throw new BizException("点位绑定失败");
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("positionId", ro.getPositionId()); //点位id
        resultMap.put("positionName", ro.getPositionName()); //点位名称
        return successResult(resultMap);
    }

    @Override
    public ResponseResultVO updateInspectionRoute(InspectionRouteRO ro) {
        checkParameterIsNotNull(String.valueOf(ro.getId()), "id不能为空");
        if (ObjectUtils.allNotNull(inspectionRouteMapper.selectOne(new QueryWrapper<InspectionRoute>().lambda().ne(InspectionRoute::getId, ro.getId()).eq(InspectionRoute::getName, ro.getName())))) {
            return ResponseResultVO.failResult("路线名称重复");
        }
        InspectionRoute inspectionRoute = new InspectionRoute();
        BeanUtils.copyProperties(ro, inspectionRoute);
        relationMapper.delete(new QueryWrapper<InspectionRelation>().lambda().eq(InspectionRelation::getRouteId, ro.getId()));
        for (String id : ro.getPositionIds()) {
            InspectionRelation inspectionRelation = new InspectionRelation();
            inspectionRelation.setId(SnowflakeIdWorker.generateId());
            inspectionRelation.setPositionId(Long.valueOf(id));
            inspectionRelation.setRouteId(inspectionRoute.getId());
            relationMapper.insert(inspectionRelation);
        }
        return updateResult(inspectionRouteMapper.updateById(inspectionRoute));
    }

    @Override
    @Transactional
    public ResponseResultVO deleteInspectionRoute(String ids) {
        checkParameterIsNotNull(ids, "id不能为空");
        List<String> idList = Arrays.asList(ids.split(","));
        relationMapper.delete(new QueryWrapper<InspectionRelation>().lambda().in(InspectionRelation::getRouteId, idList));
        return ResponseResultVO.deleteResult(inspectionRouteMapper.deleteBatchIds(idList));
    }

    @Override
    public ResponseResultVO selectInspectionRouteList(InspectionRouteRO ro) {
        Page page = new Page<Map<String, Object>>(ro.getCurrentPage(), ro.getPageSize());
        QueryWrapper<InspectionRoute> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(StringUtils.isNotBlank(ro.getName()), InspectionRoute::getName, ro.getName());
        queryWrapper.lambda().orderByDesc(InspectionRoute::getCreateTime);
        Page<InspectionRoute> pageData = inspectionRouteMapper.selectPage(page, queryWrapper);
        List<InspectionRelation> inspectionRelations = Collections.EMPTY_LIST;
        if (CollectionUtils.isNotEmpty(pageData.getRecords())) {
            inspectionRelations = relationMapper.selectList(new QueryWrapper<InspectionRelation>().lambda().in(InspectionRelation::getRouteId,
                    pageData.getRecords().stream().map(InspectionRoute::getId).collect(Collectors.toSet())));
        }
        List<InspectionPosition> inspectionPositions = Collections.EMPTY_LIST;
        if (CollectionUtils.isNotEmpty(inspectionRelations)) {
            inspectionPositions = positionMapper.selectBatchIds(inspectionRelations.stream().map(InspectionRelation::getPositionId).collect(Collectors.toList()));
        }
        List<InspectionPosition> finalInspectionPositions = inspectionPositions;
        //循环装配巡检点信息
        List<InspectionRelation> finalInspectionRelations = inspectionRelations;
        pageData.getRecords().forEach(s -> {
            List<Long> positionIds = finalInspectionRelations.stream().filter(re -> re.getRouteId().equals(s.getId())).map(InspectionRelation::getPositionId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(finalInspectionPositions)) {
                s.setPositionIds(finalInspectionPositions.stream().filter(po -> CollectionUtils.isNotEmpty(positionIds) && positionIds.contains(po.getId())).collect(Collectors.toList()));
            }
        });
        return ResponseResultVO.resultList(pageData, ro);

    }


}
